package com.yuyu.qingmang.ssoclient.Controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {

    @Value("${sso.server.url}")
    String ssoUrl;

    @GetMapping("/boss.html")
    public String boss(Model model, HttpSession session,
                        @RequestParam(value = "token",required = false) String token){

        if (token!=null){
            // 去ssoserver登录成功跳回来就会带上
            // TODO 去ssoserver获取当前token真正对应的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);
        }

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser==null){
            // 未登录
            return "redirect:"+ssoUrl+"/login.html"+"?redirect_url=http://client2.com:9001/boss.html";
        }
        else {
            List<String> users = new ArrayList<>();
            users.add("张三");
            users.add("李四");
            model.addAttribute("users",users);
            return "hello";
        }

    }
}
